import React, {memo, useCallback, useEffect, useState} from 'react';
import {Row, Col, Slider, Image, Modal, Upload} from 'antd';
import {WallWrapper} from "./style";
import {getWallList, deleteWall} from "@/network/wall.request";
import {DeleteOutlined, InboxOutlined} from "@ant-design/icons";
import setMessage from "@/utils/setMessage";
import {uploadWall} from "@/network/file.request";

const gutters = {};
const vgutters = {};
const colCounts = {};
const {Dragger} = Upload;

[8, 16, 24, 32, 40, 48].forEach((value, i) => gutters[i] = value);
[8, 16, 24, 32, 40, 48].forEach((value, i) => vgutters[i] = value);
[3, 4, 6, 8].forEach((value, i) => colCounts[i] = value);

export default memo(function Wall(props) {
  const {userId} = props;
  const [wallList, setWallList] = useState([]);
  const [gutterKey, setGutterKey] = useState(0);
  const [vgutterKey, setVgutterKey] = useState(1);
  const [colCountKey, setColCountKey] = useState(1);
  const [visible, setVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [wallId, setWallId] = useState();
  const [filename, setFilename] = useState("");

  const changeWallList = useCallback(() => {
    getWallList(userId).then(res => {
      setWallList(res);
    }).catch(console.log)
  }, [userId])

  useEffect(() => {
    changeWallList()
  }, [changeWallList])

  const handleOk = useCallback(() => {
    setConfirmLoading(true);
    deleteWall(wallId, filename).then(res => {
      if (res && res.affectedRows) {
        setMessage("删除壁纸成功", "success")
      } else {
        setMessage("删除壁纸失败", "error")
      }
      changeWallList();
      setConfirmLoading(false)
      setVisible(false);
    }).catch(error => {
      setMessage("删除壁纸失败", "error");
      setVisible(false);
      setConfirmLoading(false)
      console.log(error);
    })
  }, [wallId, filename, changeWallList])

  const handleDeleteWall = useCallback((wallId, filename) => {
    setWallId(wallId);
    setFilename(filename);
    setVisible(true);
  }, [])

  const cols = [];
  const colCount = colCounts[colCountKey];
  wallList && wallList.length > 0 && wallList.forEach(item => {
    cols.push(
      <Col key={item.id} span={24 / colCount}>
        <Image width={(colCountKey + 1) * 150}
               height={(colCountKey + 1) * 80}
               src={item.url}
               fallback=""
        />
        <DeleteOutlined
          onClick={e => handleDeleteWall(item.id, item.filename)}
          className="del-icon"
          title="删除"
          style={{top: `${vgutterKey * 4 + 12}px`, left: `${gutterKey * 4 + 12}px`}}
        />
      </Col>,
    );
  })

  const uploadProps = {
    name: "wall",
    multiple: true,
    maxCount: 9,
    showUploadList: false,
    customRequest(e) {
      const {name} = e.file;
      let type = name.split(".").pop();
      if (["jpg", "jpeg", "png", "webp", "gif"].includes(type)) {
        const formData = new FormData();
        formData.append('wall', e.file);
        uploadWall(formData).then(res => {
          if (res.code === 200) {
            setMessage("壁纸上传成功", "success");
            changeWallList();
          } else {
            setMessage("壁纸上传失败", "error");
          }
        }).catch(console.log)
      } else {
        setMessage("选择的文件不符合要求", "info");
      }
    }
  };

  cols.push(
    <Col key={0} span={24 / colCount}>
      <Dragger {...uploadProps}>
        <p className="ant-upload-drag-icon">
          <InboxOutlined/>
        </p>
        <p className="ant-upload-text">点击或拖拽到这里~</p>
        <p className="ant-upload-hint">
          上传壁纸
        </p>
      </Dragger>
    </Col>
  )

  return (
    <WallWrapper className="no-scrollbar">
      <span>横间距 (px): </span>
      <div style={{width: '30%'}}>
        <Slider
          min={0}
          max={Object.keys(gutters).length - 1}
          value={gutterKey}
          onChange={value => setGutterKey(value)}
          marks={gutters}
          step={null}
          tipFormatter={value => gutters[value]}
        />
      </div>
      <span>纵间距 (px): </span>
      <div style={{width: '30%'}}>
        <Slider
          min={0}
          max={Object.keys(vgutters).length - 1}
          value={vgutterKey}
          onChange={value => setVgutterKey(value)}
          marks={vgutters}
          step={null}
          tipFormatter={value => vgutters[value]}
        />
      </div>
      <span>每行个数:</span>
      <div style={{width: '30%', marginBottom: 48}}>
        <Slider
          min={0}
          max={Object.keys(colCounts).length - 1}
          value={colCountKey}
          onChange={value => setColCountKey(value)}
          marks={colCounts}
          step={null}
          tipFormatter={value => colCounts[value]}
        />
      </div>
      <Row gutter={[gutters[gutterKey], vgutters[vgutterKey]]}>
        <Image.PreviewGroup>
          {cols}
        </Image.PreviewGroup>
      </Row>
      <Modal
        title="删除操作"
        visible={visible}
        onOk={handleOk}
        cancelText="取消"
        okText="确定"
        confirmLoading={confirmLoading}
        onCancel={e => setVisible(false)}
      >
        <p>确定删除?</p>
      </Modal>
    </WallWrapper>
  )
})